package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.autoconfig.templates.HuanXinTemplate;
import com.tanhua.dubbo.api.FriendApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.vo.ContactVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class MessagesService {
    @DubboReference
    private FriendApi friendApi;

    @DubboReference
    private UserInfoApi userInfoApi;
    @Autowired
    private HuanXinTemplate huanXinTemplate;
    //添加好友
    public void contacts(Long userId) {
        Long id = UserHolder.getUserId();
        //保存到数据库
        friendApi.save(userId,id);
        //添加到环信上
        huanXinTemplate.addContact("hx"+id,"hx"+userId);
    }
    //查询好友
    public PageResult findFriends(Integer page, Integer pagesize) {
        //获取id
        Long userId = UserHolder.getUserId();
        //根据id查询好友
        List<Friend> list =friendApi.findByUserId(userId,page,pagesize);
        //判断是否存在
        if (CollUtil.isEmpty(list)){
            return new PageResult();
        }
        //获取所有好友id
        List<Long> ids = CollUtil.getFieldValues(list, "friendId", Long.class);
        //获取好友信息
        Map<Long, UserInfo> map = userInfoApi.findByIds(ids);
        ArrayList<ContactVo> vos = new ArrayList<>();
        for (Friend friend : list) {
            //根据id获取信息
            UserInfo userInfo = map.get(friend.getFriendId());

            ContactVo vo = ContactVo.init(userInfo);
            vos.add(vo);
        }
        return new PageResult(page,pagesize,0l,vos);
    }
}
